﻿using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using System;
using System.Text;
using System.Collections.Generic;
using AliyunAMQP;
using Microsoft.Extensions.Configuration;
using System.IO;

class Receive
{
    public static void Main()
    {
        var configuration = new ConfigurationBuilder()
                             .SetBasePath(Directory.GetCurrentDirectory())
                             .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true) //可引入不同组件来支持xml、json、ini的配置文档
                             .Build();
        var aliyunConfig = AliyunUtils.GetConfig(configuration);

        var factory = new ConnectionFactory();
        /*接入点*/
        factory.HostName = aliyunConfig.HostName;
        /*阿里云的accessKey*/
        factory.UserName = aliyunConfig.UserName;
        /*阿里云的accessSecret*/
        factory.Password = aliyunConfig.Password;
        factory.VirtualHost = aliyunConfig.VirtualHost;
        /*默认端口*/
        factory.Port = aliyunConfig.Port;
        factory.AuthMechanisms = new List<IAuthMechanismFactory>() { new AliyunMechanismFactory() };
        factory.TopologyRecoveryEnabled = true;

        using (var connection = factory.CreateConnection())
        using (var channel = connection.CreateModel())
        {
            channel.QueueDeclare(queue: aliyunConfig.QueueName, durable: false, exclusive: false, autoDelete: false, arguments: null);

            var consumer = new EventingBasicConsumer(channel);
            consumer.Received += (model, ea) =>
            {
                var body = ea.Body;
                var message = Encoding.UTF8.GetString(body.ToArray());
                Console.WriteLine(" [x] Received {0}", message);
            };
            channel.BasicConsume(queue: aliyunConfig.QueueName, autoAck: true, consumer: consumer);

            Console.WriteLine(" Press [enter] to exit.");
            Console.ReadLine();
        }
    }
}
